package com.example.stock.controller;

import com.example.stock.business.LastedOperationBusiness;
import com.example.stock.controller.vo.StockInfoVO;
import com.example.stock.excel.DailyLog;
import com.example.stock.excel.StockOperate;
import com.example.stock.model.MonthDetail;
import com.example.stock.service.*;
import com.example.stock.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@CrossOrigin(origins = "*")
@RequestMapping("operation")
@RestController
public class OperationController {

    @Autowired
    MonthDataService monthDataService;

    @Autowired
    StockOperationService stockOperationService;

    @Autowired
    StockService stockService;

    @Autowired
    UserService userService;

    @GetMapping
    Result index(@RequestParam(required = false) String stock,
                 @RequestParam(required = false) String date) {

        List<StockOperate> ret;
        if (stock != null) {
            ret = stockOperationService.operationDataGroupByStock().get(stock);
        } else if (date != null) {
            ret = stockOperationService.operationDataGroupByDate().get(date);
        } else {
            ret = stockOperationService.getOperationData().stream()
                    .sorted(Comparator.comparing(StockOperate::getDate).reversed())
                    .limit(180).toList();
        }

        return ResultGenerator.genSuccessResult(ret);
    }

    /**
     * 操作统计
     * @return
     */
    @GetMapping("sta")
    public Result sta() {
        if (!userService.isLogin()) {
            return ResultGenerator.genSuccessResult();
        }

        Map<String, List<StockOperate>> operationDataGroupByMonth = stockOperationService.operationDataGroupByMonth();

        List<Object> ret = new ArrayList<>();

        // 中证全指数据
        Map<String, List<MonthDetail>> monthRawData = monthDataService.getMonthRawData("中证全指").stream().collect(Collectors.groupingBy(MonthDetail::getDate));

        operationDataGroupByMonth.forEach((k, v) -> {
            Map<String, Object> item = new HashMap<>();

            if (monthRawData.get(k) == null) {
                return;
            }
            MonthDetail first = monthRawData.get(k).getFirst();

            item.put("date", k);
            item.put("中证全指", first.getMonthPct());
            item.put("中证全指LP", first.getLp());
            item.put("交易净额",
                    NumberUtil.floor(v.stream().mapToDouble(i -> Optional.ofNullable(i.getAmount()).orElse(0.0)).sum(), 2)
                    );
            item.put("buyCount", v.stream().filter(i -> i.getOperation().equals(OperationConstant.BUY)).count());
            item.put("sellCount", v.stream().filter(i -> i.getOperation().equals(OperationConstant.SELL)).count());
            item.put("dividendCount", v.stream().filter(i -> i.getOperation().equals(OperationConstant.DIVIDEND)).count());

            ret.add(item);
        });
        return ResultGenerator.genSuccessResult(ret);
    }

    @GetMapping("dailyLog")
    public Result dailyLog(@RequestParam(required = false) String stock) {
        List<DailyLog> dailyLogs = DataUtil.getDailyLogs();

        List<DailyLog> list;
        if (stock != null) {
            list = dailyLogs.stream().sorted(Comparator.comparing(DailyLog::getDate).reversed())
                    .filter(i -> i.getStock().equals(stock)).toList();
        } else {
            list = dailyLogs.stream().sorted(Comparator.comparing(DailyLog::getDate).reversed()).limit(550).toList();
        }

        list.forEach(i -> {
            StockInfoVO stockInfo = stockService.getStockInfo(i.getStock());
            if (stockInfo != null) {
                i.setIndustry(stockInfo.getIndustry());
            }
        });

        return ResultGenerator.genSuccessResult(
                list
        );
    }


    @Autowired
    LastedOperationBusiness lastedOperationBusiness;

    /**
     * 近期的操作
     * @return
     */
    @GetMapping("lasted")
    public Result lastedOperation(@RequestParam(required = false) String stock) {
        if (!userService.isLogin()) {
            return ResultGenerator.genSuccessResult();
        }

        if (stock == null) {
            stock = "ALL";
        }

        return ResultGenerator.genSuccessResult(lastedOperationBusiness.getLastedOperation(stock));
    }
}
